package com.util;

import com.bean.DataStatistics;
import com.bean.ShowData;
import com.google.gson.Gson;

import java.io.*;
import java.util.*;

public class FileUtil {

    public static String getRunPath() {
        File f = new File("");
        String cf = null;
        try {
            cf = f.getCanonicalPath();
        } catch (IOException e) {
            return cf;
        }
        return cf;
    }

    public static void writerFile(String content, String fileName, Boolean isAppend) {
        content = content + "\n";
        File myFile = new File(fileName);
        //如果sdcard的状态为可读写
        try {
            File myDirectory = myFile.getParentFile();
            if (!myDirectory.exists()) myDirectory.mkdir();
            //fileName为要写入的文件名,如果不存在会自动创建
            FileOutputStream fileOutputStream = new FileOutputStream(myFile, isAppend);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
            //写入文件值,content为要写入值的变量
            outputStreamWriter.write(content);
            outputStreamWriter.flush();
            outputStreamWriter.close();
            //关闭文件流
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<ShowData> readFile(String path) {
        List<ShowData> maps = new ArrayList<>();
        try {
            FileInputStream fis = new FileInputStream(path);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            while ((line = br.readLine()) != null) {
                try {
                    DataStatistics dataStatistics = new Gson().fromJson(line, DataStatistics.class);
                    long timeStr = dataStatistics.getTimeStr();
                    ShowData showData = new ShowData();
                    showData.setTime(TimeUtil.toDataStr(timeStr));
                    showData.setSuccess(dataStatistics.getSuccessNum());
                    showData.setError(dataStatistics.getErrorNum());
                    maps.add(showData);
                } catch (Exception e) {
                }
            }
            br.close();
            isr.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return maps;
    }

}
